<template>
  <div class="app-container">

    <!--新增按钮-->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input placeholder="关键词模糊搜索" v-model="listQuery.query" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter"/>

          <el-select v-model="listQuery.validFlag" placeholder="有效标志" clearable class="filter-item" style="width: 150px"
                     @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value+'('+key+')'" :value="key"/>
          </el-select>

          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>

          <el-checkbox v-model="showId" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+5">
            显示更多信息
          </el-checkbox>
        </div>
      </el-col>
    </el-row>

    <!--表格主体-->
    <el-row>
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="100px">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column v-if="showId" label="用户ID" style="width: 10%" align="center">
            <template slot-scope="scope">
              <span style="color:#008842;">{{ scope.row.userId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="公众号ID" style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.openId }}
            </template>
          </el-table-column>
          <el-table-column label="小程序ID" style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.minOpenId }}
            </template>
          </el-table-column>
          <el-table-column label="开放平台unionid" style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.unionId }}
            </template>
          </el-table-column>
          <el-table-column label="用户电话" style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userTel }}
            </template>
          </el-table-column>
          <el-table-column label="账户余额" style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.moneyBalance }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" show-overflow-tooltip>
            <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.createdTime | timeFilter}}</span>
            </template>
          </el-table-column>

          <el-table-column class-name="status-col" label="有效标志" width="110" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
                @pagination="fetchData"/>

    <!--编辑弹窗-->
    <el-dialog :visible.sync="dialogFormVisible">

      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
               style="">

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户电话" label-width="105px" prop="userTel">
              <el-input v-model="temp.userTel"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户余额" label-width="105px" prop="moneyBalance">
              <el-input v-model.number="temp.moneyBalance"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有效标志">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>

  import {getUser, getListUser, getPageUser, updateUser, createUser, deleteUser} from '@/api/manage/syUserInfo' //用户api层
  import waves from '@/directive/waves' //水波效果
  import Pagination from '@/components/Pagination' //分页插件

  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        total: 0, // 分页总数
        categories: [], //类别数据
        tableKey: 0, //表格key
        list: null, //表格对象
        listLoading: true, //表格加载框
        listQuery: { //表格查询对象
          pageNum: 1,
          pageSize: 10,
          query: '',
          validFlag: undefined
        },
        showId: false, //是否展示ID
        temp: {}, //编辑框临时变量
        dialogFormVisible: false, //编辑框显示
        dialogStatus: '', //编辑框更新插入状态
        textMap: { //编辑框标题
          update: '编辑',
          create: '创建'
        },
        rules: { //表单校验规则
          moneyBalance: [
            {required: true, message: '账户余额不能为空'},
            {type: 'number', message: '账户余额必须为数字值'}
          ]
        },
        statusOptions: { //有效无效下拉框
          '1': '有效',
          '0': '作废'
        }
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function () {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function (newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      }
    },
    /**
     *初始化生命周期
     */
    created() {
      //获取表格数据
      this.fetchData()
    },
    methods: {
      /**
       * 表格数据加载
       */
      fetchData() {
        let that = this;
        this.listLoading = true
        this.$http.all([getPageUser(this.listQuery)])
          .then(this.$http.spread(function (perms) {
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }));
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          empName: '',
          empPw: '',
          validFlag: '1',
          roleType: '1',
          timestamp: new Date()
        }
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateUser(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        let that = this;
        deleteUser({userId: row.userId}).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData();
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.page = 1
        this.fetchData()
      },
    }
  }
</script>

<style>
</style>
